<script setup lang="ts">
import { ref, computed } from 'vue';
import type { DepartmentWithChildren } from '@/api/endpoints/system/department';
import { createDepartment, updateDepartment } from '@/api/endpoints/system/department';
import { showSuccess } from '@/lib/toast';
import { DynamicForm, createDepartmentFormSchema, editDepartmentFormSchema } from '@/components/form';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';

type FormMode = 'create' | 'edit';

interface Props {
  open: boolean;
  mode: FormMode;
  department?: DepartmentWithChildren | null;
  parentDepartment?: DepartmentWithChildren | null;
}

const props = withDefaults(defineProps<Props>(), {
  department: null,
  parentDepartment: null,
});

const emit = defineEmits<{
  close: [];
  success: [];
}>();

const loading = ref(false);

// 根据模式选择 schema
const schema = computed(() => {
  return props.mode === 'create' ? createDepartmentFormSchema : editDepartmentFormSchema;
});

// 计算初始值
const initialValues = computed(() => {
  if (props.mode === 'edit' && props.department) {
    return {
      id: props.department.id,
      name: props.department.name,
      code: props.department.code || '',
      description: props.department.description || '',
    };
  }
  return undefined;
});

// 计算对话框标题和描述
const dialogTitle = computed(() => {
  return props.mode === 'create' ? '创建部门' : '编辑部门';
});

const dialogDescription = computed(() => {
  if (props.mode === 'create') {
    return props.parentDepartment
      ? `在 "${props.parentDepartment.name}" 下创建子部门`
      : '创建新的部门';
  }
  return '修改部门信息';
});

// 计算提交按钮文本
const submitButtonText = computed(() => {
  return props.mode === 'create' ? '创建部门' : '更新部门';
});

// 处理表单提交
async function handleSubmit(values: Record<string, any>) {
  try {
    loading.value = true;

    if (props.mode === 'create') {
      const departmentData = {
        ...values,
        parentId: props.parentDepartment?.id || null,
      };
      await createDepartment(departmentData as any);
      showSuccess('部门创建成功');
    } else {
      await updateDepartment(values as any);
      showSuccess('部门更新成功');
    }

    emit('success');
    handleClose();
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    loading.value = false;
  }
}

// 处理取消
function handleCancel() {
  handleClose();
}

// 处理关闭
function handleClose() {
  emit('close');
}
</script>

<template>
  <Dialog :open="open" @update:open="handleClose">
    <DialogContent class="sm:max-w-[425px]">
      <DialogHeader>
        <DialogTitle>{{ dialogTitle }}</DialogTitle>
        <DialogDescription>{{ dialogDescription }}</DialogDescription>
      </DialogHeader>

      <DynamicForm
        :schema="schema"
        :initial-values="initialValues"
        :loading="loading"
        :submit-button-text="submitButtonText"
        :show-cancel-button="false"
        @submit="handleSubmit"
        @cancel="handleCancel"
      />
    </DialogContent>
  </Dialog>
</template>
